﻿using _8Group.MES.IAppService.Area;
using _8Group.MES.IAppService.Area.Dtos;
using _8Group.MES.IAppService.Location;
using _8Group.MES.IAppService.Location.Dtos;
using _8Group.MES.Model.WM仓储管理;
using FourGroups.Project;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;

namespace _8Group.MES.AppService
{
    /// <summary>
    /// 库位实现
    /// </summary>
    [ApiExplorerSettings(GroupName = "周扬")]
    public class AreaAppService : MESAppService, IAreaAppService
    {
        private readonly IRepository<WM_Storage_Area, int> _areaRepository;

        public AreaAppService(IRepository<WM_Storage_Area, int> areaRepository)
        {
            _areaRepository = areaRepository;
        }

        /// <summary>
        /// 添加库位
        /// </summary>
        /// <param name="input">库位</param>
        /// <returns></returns>
        public async Task<int> AddArea(CreateAreaDto input)
        {
            var area = AutoMapperExt.MapTo<WM_Storage_Area>(input);
            area.CreateTime = DateTime.Now;
            await _areaRepository.InsertAsync(area);
            return 1;
        }

        /// <summary>
        /// 显示库位信息
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetAreas(string? areaName, string? areaValue, int pageIndex = 1, int pageSize = 10)
        {
            var areas = await _areaRepository.GetQueryableAsync();

            areas = areas.WhereIf(!string.IsNullOrWhiteSpace(areaName), x => x.AreaName.Contains(areaName));
            //把库位值转换为double类型
                areas = areas.WhereIf(double.TryParse(areaValue, out double value), x => x.AreaValue == value);

            int totalCount = areas.Count();
            areas = areas.OrderByDescending(x => x.CreateTime).Skip((pageIndex - 1) * pageSize).Take(pageSize);

            var result = new ResponseModel
            {
                data = areas.ToList(),
                code = "0",
                count = totalCount,
                msg = "请求成功"
            };

            return JsonConvert.SerializeObject(result, Formatting.Indented);
        }
    }
}
